package logic

import (
	"context"
	"xialou_platform/app/errorx"
	"xialou_platform/app/respx"
	"xialou_platform/services/address/model"

	"xialou_platform/services/address/rpc/internal/svc"
	"xialou_platform/services/address/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryProvinceListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryProvinceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryProvinceListLogic {
	return &QueryProvinceListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 省市联动
func (l *QueryProvinceListLogic) QueryProvinceList(in *pb.EmptyReq) (*pb.QueryProvinceListResp, error) {
	provinces, err := l.svcCtx.ProvinceModel.FindList()
	if err != nil {
		if err == model.ErrNotFound {
			return nil, errorx.NewMsgCodeError(errorx.NotFoundResourceCode, "省份不存在")
		}
		return nil, errorx.NewCodeReason(errorx.DBErrorCode, err.Error())
	}

	list := make([]*pb.QueryProvinceResp, 0)
	for _, province := range provinces {
		cities, err := l.svcCtx.CityModel.FindListByProvinceCode(province.ProvinceId)
		if err != nil {
			return nil, err
		}
		children := make([]*pb.QueryProvinceResp, 0)
		for _, city := range cities {
			tmp := &pb.QueryProvinceResp{
				Code:  respx.IDParse(city.CityId).GetInt64() / 1000000,
				Name:  city.Name,
				Level: 2,
			}
			children = append(children, tmp)
		}

		temp := &pb.QueryProvinceResp{
			Code:     respx.IDParse(province.ProvinceId).GetInt64() / 1000000,
			Name:     province.Name,
			Level:    1,
			Children: children,
		}
		list = append(list, temp)
	}

	return &pb.QueryProvinceListResp{
		List: list,
	}, nil
}
